package general

import (
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

// FetchPodStatuses 获取与指定 Controller (Deployment 或 StatefulSet) 名称一致的所有 Pods 的状态
func FetchPodStatuses(kubeconfigData string, tasks []TaskInfo) (map[string]AlarmEventResult, error) {
	clientset, err := GetClientset(kubeconfigData)
	if err != nil {
		log.Printf("创建 Kubernetes clientset 失败: %v", err)
		return nil, err
	}

	results := make(map[string]AlarmEventResult)

	for _, task := range tasks {
		labelSelector, err := getLabelSelector(clientset, task.ControllerName, task.Namespace, task.ControllerType)
		if err != nil {
			log.Printf("获取标签选择器失败: %v", err)
			results[task.TaskID] = AlarmEventResult{Error: err}
			continue
		}

		pods, err := clientset.CoreV1().Pods(task.Namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: labelSelector})
		if err != nil {
			log.Printf("列出 Pods 失败: %v", err)
			results[task.TaskID] = AlarmEventResult{Error: err}
			continue
		}

		status := analyzePods(pods.Items)
		results[task.TaskID] = status
	}

	return results, nil
}

// getLabelSelector 获取与 Controller 相关的标签选择器
func getLabelSelector(clientset *kubernetes.Clientset, controllerName, namespace, controllerType string) (string, error) {
	switch controllerType {
	case "deployment":
		deployment, err := clientset.AppsV1().Deployments(namespace).Get(context.TODO(), controllerName, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		return metav1.FormatLabelSelector(deployment.Spec.Selector), nil
	case "statefulset":
		statefulSet, err := clientset.AppsV1().StatefulSets(namespace).Get(context.TODO(), controllerName, metav1.GetOptions{})
		if err != nil {
			return "", err
		}
		return metav1.FormatLabelSelector(statefulSet.Spec.Selector), nil
	default:
		return "", fmt.Errorf("不支持的控制器类型: %s", controllerType)
	}
}

func K8sApptypeCutting(alarmConfigFormula string) (string, string, string, error) {
	var controllerType string

	// 判断是哪个类型的 Controller
	if strings.HasPrefix(alarmConfigFormula, "deployments.apps.") {
		controllerType = "deployment"
		alarmConfigFormula = strings.TrimPrefix(alarmConfigFormula, "deployments.apps.")
	} else if strings.HasPrefix(alarmConfigFormula, "statefulset.apps.") {
		controllerType = "statefulset"
		alarmConfigFormula = strings.TrimPrefix(alarmConfigFormula, "statefulset.apps.")
	} else {
		return "", "", "", fmt.Errorf("no valid controller type found in alarm config formula")
	}

	// 切分项目和应用
	projectAppParts := strings.Split(alarmConfigFormula, ".")
	if len(projectAppParts) < 2 {
		return "", "", "", fmt.Errorf("no project and app specified in configuration: %s", alarmConfigFormula)
	}

	return projectAppParts[0], projectAppParts[1], controllerType, nil
}

// analyzePods 分析 Pods 状态并返回结果
func analyzePods(pods []v1.Pod) AlarmEventResult {
	totalPods := len(pods)
	healthyPods := 0
	var firstIssue string
	var startTime time.Time

	for _, pod := range pods {
		for _, container := range pod.Status.ContainerStatuses {
			if container.State.Waiting != nil || container.State.Terminated != nil {
				if firstIssue == "" {
					if container.State.Waiting != nil {
						firstIssue = "Waiting"
					} else {
						firstIssue = "Terminated"
					}
				}
			} else if container.State.Running != nil {
				healthyPods++
				if container.State.Running.StartedAt.Time.After(startTime) {
					firstIssue = "Running"
					startTime = container.State.Running.StartedAt.Time
				}
			}
		}
	}

	healthRatio := fmt.Sprintf("%d/%d", healthyPods, totalPods)
	return AlarmEventResult{Result: healthRatio, ResultTime: startTime, ResultStatus: firstIssue}
}
